package cn.itcast.demo;

import cn.itcast.avro.User;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificDatumWriter;

import java.io.File;
import java.io.IOException;

public class AvroDemo {
    public static void main(String[] args) {
        User user=new User();
        user.setName("小明");
        user.setAge(20);
        user.setAddress("上海");
        User user2=new User("小红",17,"北京");
        User user3= User.newBuilder().setName("小华").setAge(18).setAddress("深圳").build();
       /* //序列号
        SpecificDatumWriter<User> userSpecificDatumWriter = new SpecificDatumWriter<>(User.class);
        DataFileWriter<User> userDataFileWriter = new DataFileWriter<>(userSpecificDatumWriter);
        try {
            userDataFileWriter.create(user.getSchema(),new File("users.avro"));
        userDataFileWriter.append(user);
        userDataFileWriter.append(user3);
        userDataFileWriter.append(user2);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                userDataFileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/

        //反序列话
        SpecificDatumReader<User> userSpecificDatumReader = new SpecificDatumReader<>(User.class);
        try {
            DataFileReader read = new DataFileReader<>(new File("users.avro"),userSpecificDatumReader);
            while (read.hasNext()){
                User next = (User) read.next();
                System.out.println(next);
            }
            read.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
